/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.privacy;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.Groups;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.TextView;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.util.CloseableUtil;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.friend.GroupItem;

@SuppressWarnings({"unchecked"})
public class PrivacyGroupSelectionActivity extends ListActivity {
	
	private GroupAdapter adapter;
	public static final String ID = "i";
	
	@Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        View empty = LayoutInflater.from(this).inflate(R.layout.empty_progress, null);
        ((TextView)empty.findViewById(android.R.id.text1)).setText("Please wait while we load your groups.");
        
        final ListView lv = getListView();
        lv.setEmptyView(empty);
        lv.setItemsCanFocus(false);
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
        new LoadGroupsTask(this).execute();
	}
	
	static class GroupAdapter extends BaseAdapter {
        private ArrayList<GroupItem> groups;
        private LayoutInflater inflater;

        public GroupAdapter(Context c, ArrayList<GroupItem> groups) {
            this.groups = groups;
            this.inflater = LayoutInflater.from(c);
        }

        public int getCount() {
            return groups.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }
        
        public View getView(int position, View cv, ViewGroup parent) {
        	ViewHolder holder;
            if(cv == null) {
                cv = inflater.inflate(R.layout.check_list_item_2line, parent, false);
                holder = new ViewHolder();
//                holder.icon1    = (ImageView)cv.findViewById(android.R.id.icon1);
                holder.checkbox = (CheckedTextView)cv.findViewById(android.R.id.text1);//text1 is just because there is no checkbox1
                holder.text1    = (TextView)cv.findViewById(android.R.id.title);
//                holder.text2    = (TextView)cv.findViewById(android.R.id.summary);
                
                cv.setTag(holder);
            } else {
                holder = (ViewHolder)cv.getTag();
            }
            
            final GroupItem gi = groups.get(position);
            holder.text1.setText("Group: " + gi.name);
//            holder.text3.setText("Click on this group to change its privacy");
//            holder.text4.setText(getPrivacyMode(gi.getPrivacy()));
            
            holder.checkbox.setVisibility(View.VISIBLE);
            
            return cv;
        }
        
//        private String getPrivacyMode(int privacy) {
//        	return "Privacy: " + PrivacyGroupSetupActivity.PRIVACY_OPTIONS[privacy][0];
//        }

        static class ViewHolder {
//        	ImageView icon1;
        	CheckedTextView checkbox;
        	TextView text1, text2;
        }
    }
	
	@Override
	public void finish() {
		final ListView lv = getListView();
		final SparseBooleanArray sp = lv.getCheckedItemPositions();
		final ArrayList<GroupItem> list = adapter.groups;
		
		final ArrayList<Integer> ret = new ArrayList<Integer>();
		
		int size = list.size();
		for(int i = 0; i < size; i++) {
			if(sp.get(i)) {
				ret.add(list.get(i).id);
			}
		}
		
		final Intent i = new Intent();
		i.putExtra(PrivacyGroupSetupActivity.GRANT_GROUPS, ret);
		setResult(RESULT_OK,  i);

		super.finish();
	}
	
//	@Override
//    protected void onListItemClick(ListView l, View v, int position, long id) {
//		super.onListItemClick(l, v, position, id);
//		final GroupItem gi = adapter.groups.get(position);
//		Intent i = new Intent(this, PrivacyGroupSetupActivity.class);
//		i.putExtra(PrivacyGroupSetupActivity.ID, gi.getId());
//		i.putExtra(PrivacyGroupSetupActivity.TITLE, gi.getName());
//		
//		startActivityForResult(i, 0);
//	}
	
	class LoadGroupsTask extends NetworkHandlerTask<Void, ArrayList<GroupItem>, Void> {
		private Context c;
		LoadGroupsTask(Context c) {
			this.c = c;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {

			final ContentResolver cr = c.getContentResolver();
			final ArrayList<GroupItem> list = new ArrayList<GroupItem>();
			Cursor c = null;
			try {
				
				Intent i = getIntent();
				c = cr.query(Groups.CONTENT_URI, null, Groups._ID + " <> ? AND " +  Groups.NAME + " not in (?)", 
						new String[]{"" + i.getIntExtra(ID, 0), "System Group: My Contacts"}, Groups.NAME);
				int id, name;
				if (c != null && c.moveToFirst()) {
					id    = c.getColumnIndex(Groups._ID);
					name  = c.getColumnIndex(Groups.NAME);
					do {
						list.add(new GroupItem(c.getInt(id), c.getString(name)));
					} while (c.moveToNext());
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				CloseableUtil.safeClose(c);
				c = null;
			}

			publishProgress(list);
			return null;
		}
		
		@Override
		protected void onProgressUpdate(ArrayList<GroupItem>... values) {
			super.onProgressUpdate(values);
			final ArrayList<GroupItem> list = values[0];
			adapter = new GroupAdapter(c, list);
			final ListView elv = getListView();
			elv.setAdapter(adapter);
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
		}
	}
}
